

from typing import Optional
from sqlmodel import Field

from app.models.base import BaseModel
from app.common.utils import create_any_id
from app.common.utils import get_random_str
from app.common.oss import upload_wx_avatar

class User(BaseModel, table=True):
    uid: Optional[str] = Field(default=None)
    wx_openid: Optional[str]
    apple_id: Optional[str]
    
    username: Optional[str]
    password: Optional[str]
    phone: Optional[str] = Field(default=None)
    avatar: Optional[str]
    nick_name: Optional[str]
    sex: Optional[int]
    province: Optional[str]
    city: Optional[str]
    email: Optional[str]
    
    class Config:
        orm_mode = True
        arbitrary_types_allowed = True
        
    def __init__(self):
        pass
        
    def create_wx_user(self, wx_data, avatar_local_path):
        uid = create_any_id()

        self.uid = uid
        self.wx_openid = wx_data['open_id']
        self.city = wx_data['city']
        self.nick_name = wx_data['nickname']
        if not self.nick_name:
            self.nick_name = '用户' + get_random_str(6)
        self.province = wx_data['province']
        self.sex = wx_data['sex']

        ossFilePath = 'moneygoal/avatars/' + uid + '/' + get_random_str(10) + '.png'
        upload_wx_avatar(avatar_local_path, ossFilePath)
        self.avatar = ossFilePath
        
    def create_apple_user(self, apple_data):
        self.uid = create_any_id()
        self.nick_name = apple_data['name']
        if not self.nick_name:
            self.nick_name = '用户' + get_random_str(6)
        self.email = apple_data.get('email', '')
        self.apple_id = apple_data['user']
        
    def create_common_user(self, phone):
        self.uid = create_any_id()
        self.phone = phone
        if not self.nick_name:
            self.nick_name = '用户' + get_random_str(6)
        
    
    # @validator('username', 'password')
    # def validate_fields(cls, v):
    #     if len(v.strip()) == 0:
    #         raise ValueError('参数不能为空')
    #     return v.title()